package cc.messcat.service.helpunits;

import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cc.messcat.common.model.Pager;
import cc.messcat.common.service.BaseServiceImpl;
import cc.messcat.common.util.StringUtil;
import cc.messcat.dao.area.AreaDao;
import cc.messcat.dao.helpperson.HelppersonDao;
import cc.messcat.dao.helpunits.HelpunitsDao;
import cc.messcat.entity.area.Area;
import cc.messcat.entity.helpPerson.HelpPerson;
import cc.messcat.entity.helpUnits.HelpUnits;
import cc.messcat.entity.system.McUser;
import cc.messcat.entity.vo.UnitsTotal;
import cc.messcat.util.HelpunitsControllerExcelHandler;
import cc.messcat.util.Install;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

@Service
public class HelpunitsServiceImpl extends BaseServiceImpl<HelpUnits> implements HelpunitsService {
	private static Logger log = LoggerFactory.getLogger(HelpunitsServiceImpl.class);

    @Autowired
    private HelpunitsDao helpunitsDao;
    
    @Autowired
    private HelppersonDao helpPersonDao;
    
    @Autowired
    private AreaDao areaDao;
    
    @Autowired
    private CacheManager manager;
    
    @Value("#{ configProperties['web.name'] }")
	private String projectName;


    
    @Override
    public List<HelpUnits> retrieveAllarea() {
        // TODO Auto-generated method stub
        return retrieveAllObjects();
    }

    @Override
    public Pager<HelpUnits> getPage(int pageNo, int pageSize, String Affiliation, String Unit_name, String work_telephone) {
        Map map = new HashMap<>();
        StringBuffer hql = new StringBuffer();
        hql.append("FROM HelpUnits WHERE isDel !=0 ");
        if (Affiliation != null && !"".equals(Affiliation)) {
            Affiliation = Affiliation.replaceAll(" ", "");
            hql.append(" AND Affiliation like '%" + Affiliation + "%'");
        }
        if (Unit_name != null && !"".equals(Unit_name)) {
            Unit_name = Unit_name.replaceAll(" ", "");
            hql.append(" AND Unit_name like '%" + Unit_name + "%'");
        }
        if (work_telephone != null && !"".equals(work_telephone)) {
            work_telephone = work_telephone.replaceAll(" ", "");
            hql.append(" AND work_telephone like '%" + work_telephone + "%'");
        }
        

        return this.helpunitsDao.getPagerByHql(pageNo, pageSize, hql.toString(), map);
    }

    @Override
    public void modifyHelpu(HelpUnits helpUnits) {
        helpUnits.setUpdate_time(new Date());
        modifyObject(helpUnits);
    }

    @Override
    public void addHelpu(HelpUnits helpUnits) {
        helpUnits.setDate(new Date());
        helpUnits.setUpdate_time(new Date());
        helpUnits.setIsDel("1");
        addObject(helpUnits);
    }

    @Override
    public void removeHelpu(Long id) {
        // TODO Auto-generated method stub
        removeObject(id);
    }

    @Override
    public HelpUnits get(Long id) {
        // TODO Auto-generated method stub
        return this.helpunitsDao.get(id);
    }

    @Override
    public List retrieveAllareas(Long HELP_UNIT) {
        Map map = new HashMap<>();
        String hql = "from HelpUnits where isDel !=0 and HELP_UNIT.id= :HELP_UNIT";
        map.put("HELP_UNIT", HELP_UNIT);
        return this.helpunitsDao.queryList(hql, map);
    }

    @Override
    public Pager<HelpUnits> getretrievePage(int pageNo, int pageSize, String Unit_name, String Contact_phone, String cty) {
        Map map = new HashMap<>();
        Unit_name = Unit_name.replaceAll(" ", "");
        Contact_phone = Contact_phone.replaceAll(" ", "");
        String hql = "FROM  HelpUnits AS a ,PoorVillage AS b WHERE a.isDel !=0 and a.Unit_name like '%" + Unit_name + "%' and a.Contact_phone like '%" + Contact_phone + "%' and b.cty = '" + cty + "' and a.id=b.helpPerunit ORDER BY a.date DESC";
        //String hql="from HelpUnits where Unit_name like '%"+Unit_name+"%' and Contact_phone like '%"+Contact_phone+"%'  ORDER BY date DESC";
        map.put("Unit_name", Unit_name);
        map.put("Contact_phone", Contact_phone);
        map.put("cty", cty);
        return this.helpunitsDao.getPagerByHql(pageNo, pageSize, hql, map);
    }

    @Override
    public Pager getHelpUnitsByPager(Integer pageNo, Integer pageSize, HelpUnits helpUnits,McUser user) {
    	 Map map = new HashMap<>();
    	 StringBuffer hql = new StringBuffer();
         hql.append("FROM HelpUnits WHERE 1=1 and isDel= :isDel");
         if (helpUnits.getAffiliation() != null && !"".equals(helpUnits.getAffiliation())) {
             String Affiliation = helpUnits.getAffiliation().replaceAll(" ", "");
              hql.append(" AND Affiliation like '%" + Affiliation + "%'");
          }
         if (helpUnits.getUnit_name() != null && !"".equals(helpUnits.getUnit_name())) {
            String Unit_name = helpUnits.getUnit_name().replaceAll(" ", "");
             hql.append(" AND Unit_name like '%" + Unit_name + "%'");
         }
         if (helpUnits.getWork_telephone() != null && !"".equals(helpUnits.getWork_telephone())) {
           String  work_telephone = helpUnits.getWork_telephone().replaceAll(" ", "");
             hql.append(" AND Contact_phone like '%" + work_telephone + "%'");
         }
         //乡
         if(user.getUserLevel().getLevel() == 4){
      	   if(helpUnits.getCountry()!= null && !"".equals(helpUnits.getCountry())){
      		 Area area = areaDao.getAreaByCode(helpUnits.getCountry());
             hql.append(" AND country like '%" + area.getArea() + "%'");
  	   }else{
  		   Area area = areaDao.getAreaByCode(user.getArea().getAreaCode());
         	   String country = area.getArea(); 
             hql.append(" AND country like '%" + country + "%'");
  	   } 
         }else{
          	 if(helpUnits.getCountry() != null && !"".equals(helpUnits.getCountry())){
        		      Area area = areaDao.getAreaByCode(helpUnits.getCountry());
                   hql.append("  AND country like '%" + area.getArea() + "%'");
        	   }
         }

         map.put("isDel", "1");

         return this.helpunitsDao.getPagerByHql(pageNo, pageSize, hql.toString(), map);
    }
    
	/**
	 * 按条件列出帮扶单位
	 * 
	 * @return
	 */
	@Override
	public Pager listHelpUnit(Integer pageNo, Integer pageSize, HelpUnits helpUnits, McUser user) {
		StringBuffer hql = new StringBuffer();
		hql.append(" FROM HELPUNITS WHERE is_del= '1'");
		if (helpUnits.getAffiliation() != null && !"".equals(helpUnits.getAffiliation())) {
			String Affiliation = helpUnits.getAffiliation().replaceAll(" ", "");
			hql.append(" AND affiliation like '%" + Affiliation + "%'");
		}
		if (StringUtils.isNotBlank(helpUnits.getUnit_name())) {
			String Unit_name = helpUnits.getUnit_name().replaceAll(" ", "");
			hql.append(" AND unit_name like '%" + Unit_name + "%'");
		}
		if (helpUnits.getWork_telephone() != null && !"".equals(helpUnits.getWork_telephone())) {
			String work_telephone = helpUnits.getWork_telephone().replaceAll(" ", "");
			hql.append(" AND Contact_phone like '%" + work_telephone + "%'");
		}
		// 乡
		if (user.getUserLevel().getLevel() == 4) {
			Area userArea = user.getArea();
			if( userArea != null && StringUtils.isNotBlank(userArea.getAreaCode())) {
				Area area = areaDao.getAreaByCode(user.getArea().getAreaCode());
				String country = area.getArea();
				hql.append(" AND country like '%" + country + "%'");
			} else {
				hql.append(" AND country like 'none'");
			}
		} else {
			if (helpUnits.getCountry() != null && !"".equals(helpUnits.getCountry())) {
				Area area = areaDao.getAreaByCode(helpUnits.getCountry());
				hql.append("  AND country ='" + (area != null ? area.getArea() : "none") + "'");
			}
		}

		String fields = "select id as id ,province as province,city as city,county as county,"
			+ " country as country,unit_name as unitName,unit_type as unitType,affiliation as affiliation, work_telephone as tel,"
			+ " contacts as contacts, contact_phone as ContactTel,unit_address as address,Postal_Code as postCode ,Mail_box as mail, Unit_id as unitNumber ";
		pageNo = ((pageNo == null || pageNo < 1) ? 1 : pageNo);
		pageSize = ((pageSize == null || pageSize < 1) ? 8 : pageSize);
		return helpunitsDao.listHelpUnit(pageNo, pageSize, fields + hql.toString(), "select count(*) " + hql.toString());
	}

    @Override
	public void modifyHelpuNew(HelpUnits helpUnits) {
		// TODO Auto-generated method stub
		if(helpUnits!=null && helpUnits.getId()!=null){
			HelpUnits hu = this.retrieveObject(helpUnits.getId());
			if(hu!=null){
				hu.setProvince(helpUnits.getProvince());
				hu.setCity(helpUnits.getCity());
				hu.setCounty(helpUnits.getCounty());
				hu.setCountry(helpUnits.getCountry());
				hu.setUnit_name(helpUnits.getUnit_name());
				hu.setUnit_type(helpUnits.getUnit_type());
				hu.setAffiliation(helpUnits.getAffiliation());
				hu.setWork_telephone(helpUnits.getWork_telephone());
				hu.setContacts(helpUnits.getContacts());
				hu.setContact_phone(helpUnits.getContact_phone());
				hu.setUnit_address(helpUnits.getUnit_address());
				hu.setPostal_Code(helpUnits.getPostal_Code());
				hu.setMail_box(helpUnits.getMail_box());
				hu.setUnit_id(helpUnits.getUnit_id());
				
				List<HelpPerson> helpPerson = hu.getHelpPerson();
		  		for (HelpPerson hp : helpPerson) {
		  			hp.setHelpUnitName(helpUnits.getUnit_address());
		  			hp.setAffiliation(helpUnits.getAffiliation());
		  			hp.setUnit_name(helpUnits.getUnit_name());
				}
				this.modifyHelpu(hu);
			}
		}
	}

    /**
     * 帮扶单位数
     */
	@Override
	public List unitsNr() {
//		Element element = manager.getCache("indexStatistics").get("unitsNumber");
//		if(element != null) {
//			return (List) element.getObjectValue();
//		}


//		String hql = "select area FROM Area where fatherId = '3' ";
//		List<String> country = helpunitsDao.find(hql);
		List<Map<String, Object>> tempPTs = new ArrayList<>();
//		for (String cy : country) {
//			String hql_2 = "FROM HelpUnits where country = '"+cy+"' AND isDel = '1'  and Unit_name <> ''";
//			int t = helpunitsDao.find(hql_2).size();
//			tempPTs.add(new UnitsTotal(cy,t));
//		}
		List<UnitsTotal> result = new ArrayList<>();
		for(Map<String, Object> e : helpunitsDao.helpUntiStatistics()) {
			UnitsTotal unitsTotal = new UnitsTotal();
			unitsTotal.setName(e.get("name").toString());
			unitsTotal.setValue(e.get("value") != null ? ((BigInteger)(e.get("value"))).intValue() : 0);
			result.add(unitsTotal);
		}
		
		manager.getCache("indexStatistics").put(new Element("unitsNumber", result));
		return result;
	}
	
	
	/**
	 * 单位导入
	 */
	@SuppressWarnings("unchecked")
	@Override
	public  String adduploadFile(String file, HttpSession session,McUser mcUser) throws Exception {
		// 获取本地exc全路径
		String classPath=this.getClass().getClassLoader().getResource("").getPath();
		String	excelFile=classPath.substring(1,classPath.indexOf("/WEB-INF"))+file;
		File files = new File(excelFile);
		if(!files.exists()){
			return "NO_URL";
		}
		// 解析Excel文件
		Map data = new HashMap();
		try {
			data = HelpunitsControllerExcelHandler.readExcel(excelFile);
			if(StringUtil.isNotBlank((String)data.get("errInfo"))){
				return data.get("errInfo").toString();
			}
			data.remove("errInfo");
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			//最后删除上传文件
			files.delete();
		}
		
		//数据比较：获取所有单位
		long dataTimeS = System.currentTimeMillis();
//		Map<String, HelpUnits> helpUnMap = gainHelpUnMap();
		Map<String, Long> helpUnMap = gainHelpUnMap();
		//储存已插入的单位
		Map<String,Long> helpUnMaps = new HashMap<String,Long>();
		long dataTimeE = System.currentTimeMillis();
		log.info(dataTimeE-dataTimeS+"S>>>>>>>>>>>>>>>扶贫单位导入 获取数据耗时");
		
		//储存需要添加的帮扶单位
		List<Map<String, Object>> addHelpuList= new ArrayList<Map<String, Object>>();
		//储存需要更新的帮扶单位
		List<Map<String, Object>> upHelpuList= new ArrayList<Map<String, Object>>();
		
		// 依次将data中的数据映射到Signind对象并保存到数据库
		Set<Object> keySet = data.keySet();
		for (Object obj : keySet) {
			ArrayList<HelpUnits> helpUnitsList = new ArrayList<HelpUnits>();
			helpUnitsList = (ArrayList<HelpUnits>) data.get(obj);
			for (HelpUnits helpExc : helpUnitsList) {
				try { 
					//储存添加或者更新帮扶单位
					addOrUpdateHelpUnits(mcUser, helpUnMap,helpUnMaps, helpExc,addHelpuList,upHelpuList);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		String sql= null;
		// 添加 处理
		if (addHelpuList != null && addHelpuList.size() > 0) {
			sql = "insert into helpunits(Unit_name,Affiliation,Unit_type,Work_telephone,Contacts,Contact_phone,Unit_address,Postal_Code,Mail_box,is_del,Province,City,County,Country,Annual,One_man,Date,Card_time) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			Install.executeBatch(sql, 18, addHelpuList);
		}
		// 更新 处理
		if (upHelpuList != null && upHelpuList.size() > 0) {
			sql = "update helpunits set Unit_name=?,Affiliation=?,Unit_type=?,Work_telephone=?,Contacts=?,Contact_phone=?,Unit_address=?,Postal_Code=?,Mail_box=?,is_del=?,Province=?,City=?,County=?,Country=?,Annual=?,Modifier=?,Update_time=? where id=? ";
			Install.executeBatch(sql, 18, upHelpuList);
		}
		//清除数据
		helpUnMap.clear();
		helpUnMaps.clear();
		addHelpuList.clear();
		upHelpuList.clear();
		return "T";

	}
	/**
	 * 储存添加或者更新帮扶单位
	 * 
	 * @param mcUser
	 * @param helpUnMap
	 * @param helpUnMaps 
	 * @param helpExc
	 * @param addHelpuList 
	 * @param upHelpuList 
	 * @param helpUnits
	 */

	public void addOrUpdateHelpUnits(McUser mcUser, Map<String, Long> helpUnMap, Map<String, Long> helpUnMaps, HelpUnits helpExc, List<Map<String, Object>> addHelpuList, List<Map<String, Object>> upHelpuList) {
		HelpUnits helpUnits = new  HelpUnits();
		//帮扶单位ID
		Long hId = null ;
		// 根据帮扶单位名称判断系统内是否存在对应的帮扶单位信息，存在更新不存在添加(更新有两种情况)
		//相同乡镇下帮扶单位名称不能重复，不同乡镇下帮扶单位名称可以重复
		// 一.在新插入的helpUnMaps帮扶单位里面找是否有该数据
		String he_Country = helpExc.getUnit_name()+"_"+helpExc.getProvince().split(" ")[3];
		if (helpUnMaps.containsKey(he_Country)) {
			hId = helpUnMaps.get(he_Country);
			helpUnits.setId(hId);
		}
		// 二.在数据库查找helpUnMap帮扶单位是否有该数据
		else if (helpUnMap.containsKey(he_Country)) {
			hId = helpUnMap.get(he_Country);
			helpUnits.setId(hId);
		}
		helpUnits.setUnit_name(helpExc.getUnit_name());
		helpUnits.setAffiliation(helpExc.getAffiliation());
		helpUnits.setUnit_type(helpExc.getUnit_type());
		helpUnits.setWork_telephone(helpExc.getWork_telephone());
		helpUnits.setContacts(helpExc.getContacts());
		helpUnits.setContact_phone(helpExc.getContact_phone());
		helpUnits.setUnit_address(helpExc.getUnit_address());
		helpUnits.setPostal_Code(helpExc.getPostal_Code());
		helpUnits.setMail_box(helpExc.getMail_box());
		helpUnits.setIsDel("1");
		// 行政区划
		if (StringUtil.isNotBlank(helpExc.getProvince())) {
			String[] istraStr = helpExc.getProvince().split(" ");
			if (istraStr.length >= 1)
				helpUnits.setProvince(istraStr[0]);
			if (istraStr.length >= 2)
				helpUnits.setCity(istraStr[1]);
			if (istraStr.length >= 3)
				helpUnits.setCounty(istraStr[2]);
			if (istraStr.length >= 4)
				helpUnits.setCountry(istraStr[3]);
		}
//		helpUnits.setAnnual(new SimpleDateFormat("YYYY").format(new Date()));
		if (hId != null && !helpUnMaps.containsKey(helpExc.getUnit_name())) {
			helpUnits.setModifier(mcUser.getUsername());// 修改人
			helpUnits.setUpdate_time(new Date());
			///////////////////STA（获取Batch数据）
			//储存需要更新的Map
		    Map<String, Object> upHelpuMap = HelpUnitBatchPara(helpUnits,1);
		    upHelpuList.add(upHelpuMap);
			//////////////////END
//			this.helpunitsDao.update(helpUnits);
		  //储存已更新或添加的帮扶单位信息
		    helpUnMaps.put(helpUnits.getUnit_name(), helpUnits.getId());
		}  else if (hId == null){
			helpUnits.setOne_man(mcUser.getUsername());// 制单人
			helpUnits.setDate(new Date());
			helpUnits.setCard_time(new Date());// 制单时间
			///////////////////STA（获取Batch数据）
			//储存需要添加的Map
			Map<String, Object> addHelpuMap = HelpUnitBatchPara(helpUnits,0);
			addHelpuList.add(addHelpuMap);
			///////////////////END
//			this.helpunitsDao.save(helpUnits);
			//储存已更新或添加的帮扶单位信息
		    helpUnMaps.put(helpUnits.getUnit_name()+"_"+helpUnits.getCountry(), helpUnits.getId());
		    
		}
	}

	/**
	 * 获取Batch数据
	 * @param helpUnits
	 * @param type
	 *            0添加 1更新 2删除
	 * @return
	 */
	public Map<String, Object> HelpUnitBatchPara(HelpUnits helpUnits, Integer type) {
		Map<String, Object> addHelpuMap = new HashMap<String, Object>();
		addHelpuMap.put("1", helpUnits.getUnit_name());
		addHelpuMap.put("2", helpUnits.getAffiliation());
		addHelpuMap.put("3", helpUnits.getUnit_type());
		addHelpuMap.put("4", helpUnits.getWork_telephone());
		addHelpuMap.put("5", helpUnits.getContacts());
		addHelpuMap.put("6", helpUnits.getContact_phone());
		addHelpuMap.put("7", helpUnits.getUnit_address());
		addHelpuMap.put("8", helpUnits.getPostal_Code());
		addHelpuMap.put("9", helpUnits.getMail_box());
		addHelpuMap.put("10", helpUnits.getIsDel());
		addHelpuMap.put("11", helpUnits.getProvince());
		addHelpuMap.put("12", helpUnits.getCity());
		addHelpuMap.put("13", helpUnits.getCounty());
		addHelpuMap.put("14", helpUnits.getCountry());
//		addHelpuMap.put("15", helpUnits.getAnnual());
		if (type == 0) {
			addHelpuMap.put("16", helpUnits.getOne_man());
			addHelpuMap.put("17", helpUnits.getDate());
			addHelpuMap.put("18", helpUnits.getCard_time());
		}
		if (type == 1 && helpUnits.getId() != null) {
			addHelpuMap.put("16", helpUnits.getModifier());
			addHelpuMap.put("17", helpUnits.getUpdate_time());
			// id
			addHelpuMap.put("18", helpUnits.getId());

		}

		return addHelpuMap;
	}


 
	/**
	 * 获取所有单位数据遍历到Map
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map<String, Long> gainHelpUnMap() {
	/*	Map<String, HelpUnits> helpUnMap = new HashMap<String, HelpUnits>();
		Map map = new HashMap<>();
		map.put("annual", new SimpleDateFormat("YYYY").format(new Date()));
		// map.put("Unit_name", helpExc.getUnit_name());
		List<HelpUnits> Helplist = this.helpunitsDao.queryList("from HelpUnits where isDel='1' and  annual=:annual", map);
		for (HelpUnits h : Helplist) {
			helpUnMap.put(h.getUnit_name(), h);
		}
		*/
		Map<String, Long> helpUnMap = new HashMap<String, Long>();
		Map map = new HashMap<>();
		List<Object[]> Helplist = this.helpunitsDao.queryList("select Unit_name , id , country from HelpUnits  where isDel='1'", map);
		 for (Object[] h : Helplist) {
			 helpUnMap.put((String) h[0]+"_"+h[2], (Long) h[1]);
		}
		return helpUnMap;
	}

	@Override
	public void removeAddhelpoors(Long id, String sid) {
		
		List<HelpPerson> helpPersons = helpPersonDao.getByHelpUnit(id);
		for (HelpPerson hp : helpPersons) {
			helpPersonDao.updateHelpPersonAndPoorFamily(hp.getId());
		}
	
		helpunitsDao.removeAddhelpoors( id,  sid);
	}

	@Override
	public List<?> getHelpUnits(Long id) {
		
		return helpunitsDao.getHelpUnits(id);
	}
}
